#!/bin/bash
###
 # @Author: yoola youlikesoilove@qq.com
 # @Date: 2025-01-07 00:42:33
 # @LastEditors: yoola youlikesoilove@qq.com
 # @LastEditTime: 2025-01-08 02:07:37
 # @FilePath: \CrabSystemProject\service_center\install.sh
 # @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
### 

# ======================================================
# 安装需要的环境依赖
separator="\n======================================================"
echo "install Required environment ..."
sudo apt-get update && sudo apt-get upgrade
sudo apt install git build-essential gcc make cmake libssl-dev python3-pip libgl1
sudo apt install nlohmann-json3-dev libopencv-dev cmake
pip3 install schedule



# ======================================================
# 编译过程
echo -e $separator
echo "build the func app ..."
PROJECT_ROOT=$(pwd)
# 构建目录
BUILD_DIR="$PROJECT_ROOT/build"
# 创建构建目录
if [ ! -d "$BUILD_DIR" ]; then
    mkdir "$BUILD_DIR"
fi

# 进入构建目录
cd "$BUILD_DIR"
# 运行 CMake
cmake ..
# 如果 CMake 失败，退出脚本
if [ $? -ne 0 ]; then
    echo "CMake configuration failed."
    exit 1
fi
# 运行 make 构建所有目标
make -j$(nproc)
# 如果 make 失败，退出脚本
if [ $? -ne 0 ]; then
    echo "Build failed."
    exit 1
fi

# 打印构建成功信息
echo "Build successful. Executables are available in the build directory."
# 返回到项目根目录
cd "$PROJECT_ROOT"



# ======================================================
# 创建应用文件夹
echo -e $separator
echo "copy app to app directory ..."
echo "create dir /home/pi/app"
mkdir -p /home/pi/app
echo "create dir /home/pi/log"
mkdir -p /home/pi/log
# 拷贝照片管理系统到指定目录下
echo "copy PictureManager to /home/pi/app/"
cp -r ./src/PictureManager/UpdatePhoto.py /home/pi/app/
echo "copy Crab_CapturePhotoApp to /home/pi/app/"
cp -r "$PROJECT_ROOT"/build/bin/Crab_CapturePhotoApp /home/pi/app/
echo "copy main_node to /home/pi/app/"
cp -r "$PROJECT_ROOT"/build/bin/main_node /home/pi/app/
echo "copy service_manager.sh to /home/pi/"
cp -r "$PROJECT_ROOT"/service_center/service_manager.sh /home/pi/
chmod +x /home/pi/service_manager.sh 
# 拷贝对应的配置文件 - > 会默认生成一个，暂无需配置
# echo -e $separator
# echo "copy defalut config file ..."


echo -e $separator
echo "enable service ..."
service_dir="$PROJECT_ROOT/service_center"
echo "enable $service_dir/Crab_CapturePhotoApp.service"
sudo systemctl enable "$service_dir"/Crab_CapturePhotoApp.service

echo "enable $service_dir/Crab_CapturePhotoApp.service"
sudo systemctl enable "$service_dir"/main_node.service

echo "enable $service_dir/upload_node.service"
sudo systemctl enable "$service_dir"/upload_node.service

echo -e $separator
echo "start service ..."
sudo systemctl daemon-reload
echo "start Crab_CapturePhotoApp.service"
sudo systemctl start Crab_CapturePhotoApp.service
echo "start main_node.service"
sudo systemctl start main_node.service
echo "start upload_node.service"
sudo systemctl start upload_node.service

echo -e $separator
echo "install ok !!!!"